package com.haiyou.common.util;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

/**
 * @author chenzeke
 */
@Slf4j
public class Md5Util {

    public static final String MD5_MIX = "haiyou-2019";
    private static final String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    public static void main(String[] args) {
        System.out.println(md5Mix("123456"));
    }

    public static String md5Mix(String pwd) {
        String chartSet = "utf-8";
        if (pwd == null) {
            return null;
        } else {
            String md5Pwd = MD5Encode(MD5_MIX + pwd, chartSet);
            return MD5Encode(md5Pwd, chartSet);
        }
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();

        for (int i = 0; i < b.length; ++i) {
            resultSb.append(byteToHexString(b[i]));
        }

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (b < 0) {
            n = b + 256;
        }
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname != null && !"".equals(charsetname)) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            }
        } catch (Exception e) {
            log.error("MD5Encode error==>" + e.getMessage(), e);
        }

        return resultString;
    }
}
